//
//  CWBarButtonItem.m
//  CWDevelop
//
//  Created by LittoCats on 7/15/14.
//  Copyright (c) 2014 Littocats. All rights reserved.
//

#import "CWBarButtonItem.h"
#import "CWViewStaticTouchEventAnalyzer.h"

#import "UIImage+CW.h"
#import "UIColor+CW.h"
#import "NSObject+CW.h"

@implementation CWBarButtonItem


- (instancetype)initWithAttributes:(NSMutableDictionary *)attributes
{
    NSString *title = attributes[@"text"];
    UIColor *titleColor = [UIColor colorWithScript:attributes[@"textColor"]];
    NSString *titleFont = attributes[@"textFont"];
    UIImage *image = [UIImage imageWithScript:attributes[@"image"]];
    if (image) {
        self = [self initWithImage:image style:UIBarButtonItemStylePlain target:[CWViewStaticTouchEventAnalyzer defaultAnalyzer] action:@selector(buttonItemClicked:)];
    }else if (title && [title isKindOfClass:[NSString class]]){
        self = [self initWithTitle:title style:UIBarButtonItemStylePlain target:[CWViewStaticTouchEventAnalyzer defaultAnalyzer] action:@selector(buttonItemClicked:)];
        NSMutableDictionary *titleAttributes = [NSMutableDictionary new];
        if (titleColor) [titleAttributes setObject:titleColor forKey:NSForegroundColorAttributeName];
        if (titleFont) [titleAttributes setObject:titleFont forKey:NSFontAttributeName];
        
        [self setTitleTextAttributes:titleAttributes forState:UIControlStateNormal];
    }
    [self setOnClickEvent:attributes[@"onClick"]];
    self.attributes = attributes;
    return self;
}

- (void)setOnClickEvent:(id)onClickEvent
{
    if (!onClickEvent) return;
    [[CWViewStaticTouchEventAnalyzer defaultAnalyzer] addTouchResponder:onClickEvent toBarButtonItem:self];
}
@end
